﻿using FrameWorkCore.DynamicWebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Repository.FrameWorkCore;
using Repository.Repository;
using EntityFrameWorkCore;
using Entity;
using Utility.Helper;
using Entity.UserRoles;

namespace Application
{

    public abstract class ApplicationServiceBase: ApplicationService
    {
        public IHttpContextAccessor HttpContextAccessor { get; set; }

        public IUnitOfWorkManager UnitOfWorkManager { get; set; }

        public IRepository<User, Guid, DefaultDbContext> UserRep { get; set; }

        public IRepository<Role, Guid, DefaultDbContext> RoleRep { get; set; }

        public IRepository<UserRole, Guid, DefaultDbContext> UserRoleRep { get; set; }

        protected async ValueTask<User> GetCurrentUserAsync()
            => await UserRep.GetAsync(Guid.Parse(HttpContextAccessor.HttpContext.User.Claims.First(x => x.Type == "SubjectId").Value));

        protected async ValueTask<List<Role>> GetCurrentUserRolesAsync()
        {
            var user = await UserRep.GetAsync(Guid.Parse(HttpContextAccessor.HttpContext.User.Claims.First(x => x.Type == "SubjectId").Value));
            var userRoleIds = (await UserRoleRep.GetAllListAsync(x => x.UserId == user.Id)).Select(c => c.RoleId);
            var roles = await RoleRep.GetAllListAsync(x => userRoleIds.Contains(x.Id));
            return roles;
        }


        protected T MapTo<T>(object source)
            => AutoMapperExtension.MapTo<T>(source);

        protected T Map<T>( object source, T target)
            => AutoMapperExtension.Map<T>(source, target);
    }
}
